package com.lesserpand.springcloudalibabacore.config.redis.listener;

import org.redisson.api.RQueue;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * @author bailuo
 * @version 2.0
 * @Description 项目启动即监听。伪监听实现方式，没有找到官方提供的监听延迟队列实际消费队列的方法，只能用这种伪监听替代，会一直循环监听真正的队列是否有数据，存在一定隐患
 * @Date Created in 2019/1/15 9:45
 * ApplicationRunner
 */
@Component
public class RedissonQueueListener implements ApplicationRunner {

    private static final Logger LOGGER = LoggerFactory.getLogger(RedissonQueueListener.class);

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        RQueue<String> distinationQueue = redissonClient.getQueue("message_queue");
        while (true) {
            while (null != distinationQueue.peek()) {
                String msg = distinationQueue.poll();
                LOGGER.info(msg);
                // 可以处理业务逻辑，比如下单，通知支付，由于使用rabbitmq已经写过栗子，这里不再重复写。
            }
            Thread.sleep(1000);
        }
    }
}
